package cool.xiaokang.familyaccount.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cool.xiaokang.familyaccount.dao.UserDao;
import cool.xiaokang.familyaccount.pojo.User;
import cool.xiaokang.familyaccount.service.UserService;
import cool.xiaokang.familyaccount.utils.CryptographyUtil;
import cool.xiaokang.familyaccount.utils.PageBean;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;

	public void save(User user) {
		userDao.merge(user);
	}

	public void saveUser(User user) throws Exception {
		String md5PWD = CryptographyUtil.md5(user.getUser_password(),
				CryptographyUtil.md5(CryptographyUtil.FAMILY, user.getUser_name()));
		user.setUser_password(md5PWD);
		user.setState('0');
		user.setRegister_date(new Date());
		user.setLevel(user.getLevel());
		// 默认头像
		if (user.getLevel() == 0) {
			user.setFace("img/userface/user15.gif");
		} else if (user.getLevel() == 1) {
			user.setFace("img/userface/user0.gif");
		}
		userDao.merge(user);
	}

	public void update(User user) {
		userDao.update(user);
	}

	public void persistUser(User user) {
		userDao.persistUser(user);
	}

	// 检查用户名
	@Override
	public boolean findUserByName(String user_name) {
		User user = userDao.findUserByName(user_name);
		if (user != null) {
			return true;
		} else {
			return false;
		}
	}

	// 修改密码
	@Override
	public void updatePwd(User user) {
		User user2 = userDao.load(user.getUser_id());
		String newpwd = CryptographyUtil.md5(user.getUser_password(),
				CryptographyUtil.md5(CryptographyUtil.FAMILY, user2.getUser_name()));
		userDao.executeUpdate("user.update", newpwd, user.getUser_id());

	}

	// 检查email
	@Override
	public boolean findUserByEmail(String email) {
		User user = userDao.findUserByEmail(email);
		if (user != null) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void pageQuery(PageBean pb) {
		userDao.pageQuery(pb);
	}

	// 封禁用户
	@Override
	public void stop(String user_ids) {
		String[] userIds = user_ids.split(",");
		for (String user_id : userIds) {
			userDao.executeUpdate("user.stop", Long.parseLong(user_id));
		}
	}

	// 解封用户
	@Override
	public void open(String user_ids) {
		String[] userIds = user_ids.split(",");
		for (String user_id : userIds) {
			userDao.executeUpdate("user.open", Long.parseLong(user_id));
		}
	}

	// 修改用户等级
	@Override
	public void editLevel(User user) {
		userDao.executeUpdate("user.editlevel", user.getLevel(), user.getUser_id());
	}

	@Override
	public User findUserByKeyWord(String keyword) {
		return userDao.getUserByName(keyword);
	}
}
